utils.baseApiUrl="http://api.xunbaozl.com/v2/";
twUtil.baseApiUrl="http://api.xunbaozl.com/v2/";

$(document).ready(function() {
	//modulesId  3.0首页 精选:15 16;
	var editHtml = "";
	var moduleId;
	var featuleType;
	var modulesName;
	var featureJsonValues;
	var bannerChoose = "";
	var baseEditHtml = '<div  class="diy-ctrl-item" >'+
	                   '<div class="item ctrl-title">基础配置</div>'+
		               '<div class="item" style="height:90px;" index="_index_placeholder">'+
		               		'<input class="show_head_checkbox" type="checkbox"name="isShowhead">是否显示head'+
		               		'<span class="devide"></span>'+
		               		'head名称 <input type="text"name="headName" class="header_name">'+
		               		'<br/>'+
		               		'<input class="show_line_checkbox" type="checkbox" name="isShowhead">是否显示line'+
		               '</div>';
	var bannerEditHtml = baseEditHtml+'<div class="item ctrl-title">banner选择版式</div><div class="item"><input type="radio"name="bannerFormat"value="newFormat" checked>版式1(新版)<span class="devide"></span><input type="radio"name="bannerFormat"value="oldFormat">版式2(老版)<span class="devide"></span><span><a target="navTab" href="#"><span class="btn bannerFormatEdit">编辑</span></a></span></div></div>';
	var specialEditHtml = baseEditHtml+'<div class="item ctrl-title">专题管理</div><div class="item"><span><a target="navTab" href="#"><span class="btn specialManage">管理专题</span></a></span><span class="devide"></span><span><a target="navTab" href="#"><span class="btn relateManage">关联专题</span></a></span></div></div>';
	var boutiqueEditHtml = baseEditHtml+'<div class="item ctrl-title">精品拍选择版式</div><div class="item"><input type="radio"name="auction"value="newAuctionFormat" checked>版式1<span class="devide"></span><input type="radio"name="auction"value="oldAuctionFormat">版式2</div></div>';
	var pictureEditHtml = baseEditHtml+'<div class="item ctrl-title">图片专题选择版式</div><div class="item"><input type="radio"name="picture"value="picFormatOne">版式1<span class="devide"></span><input type="radio"name="picture"value="picFormatTwo">版式2<span class="devide"></span><span class="devide"></span><input type="radio"name="picture"value="picFormatThree">版式3<span class="devide"></span><span class="devide"></span><input type="radio"name="picture"value="picFormatFour">版式4<span class="devide"></span><span><a target="navTab" href="#"><span class="btn picEdit">编辑</span></a></span></div></div>';
	var categoryEditHtml = baseEditHtml+'<div class="item ctrl-title">热门分类选择版式</div><div class="item"><input type="radio"name="categoryFormat"value="newcateFormat" checked>版式1<span class="devide"></span><input type="radio"name="categoryFormat"value="oldcateFormat">版式2<span class="devide"></span><span><a target="navTab" href="#"><span class="btn cateFormatEdit">编辑</span></a></span></div></div>';
	var greatGoodsEditHtml = baseEditHtml+'<div class="item ctrl-title">精选好物管理</div><div class="item"><span><a target="navTab" href="#"><span class="btn greatGoodsManage">管理精选好物</span></a></span><span class="devide"></span><span><a target="navTab" href="#"><span class="btn relateGreatGood">关联精选好物</span></a></span></div></div>';
	var masterEditHtml = baseEditHtml+'<div class="item ctrl-title">大师推荐</div><div class="item"><span><a target="navTab" href="#"><span class="btn masterRec">编辑</span></a></span><span class="devide"></span></div></div>';
	var endEditHtml = '<div class="item" <span>'+
            			'<a target="navTab" href="#">'+
            				'<span class="btn baseEdit">编辑</span>'+
            				'</a>'+
            				'</span></div></div>';
	var list = [];
	utils.jsonp({
		url: "modules/getAllModule",
		success: function(result) {
			var modulesNaviHtml = '选择模块:<select>';
			for (var i = 0; i < result.data.length; i++) {
				modulesNaviHtml += '<option name=' + result.data[i].name + ' value=' + result.data[i].id + '>' + result.data[i].name + '</option>';
			}
			modulesNaviHtml += '</select>';
			$(".selectContainer").html(modulesNaviHtml);
			moduleId = $("select").val();
			initModuleData(moduleId, result);
			$(".diy-cirl").css("display", "none");

			$("select").change(function() {
				$(".diy-cirl").css("display", "none");
				moduleId = $("select").val();

				initModuleData(moduleId, result);

			})

		}
	})

	//不同模块
	function initModuleData(moduleId, result) {

		var diyHtml = template("diy-actions-tpl-select-modules", {"list": result.data});
		$(".diy-actions").html(diyHtml);

		utils.jsonp({
			url: "modules/getFullModuleById?moduleId=" + moduleId,
			params: {
				"isEditRequest": 1
			},
			success: function(results) {

				$(".j-pagetitle").html(results.data.name); //设置模块名称
				list = results.data.list;
				editModule();

			}
		})

		//增加一个模块
		$(".j-page-addModule").click(function() {

			featuleType = $(this).attr("featuleType");
			modulesName = "3.0 " + $(this).attr("moduleName");

			var extData = $(this).attr("extData");
			var featureObj = {};
			featureObj.moduleId = parseInt(featuleType);
			featureObj.name = modulesName;
			if (extData != null) {
				featureObj.extData = extData;
			}

			var jsonObjStr = JSON.stringify(featureObj);
			utils.jsonp({
				url: "modules/addFeatureByModuleId",
				type: "POST",
				params: {
					"jsonValue": jsonObjStr,
					"moduleId": parseInt(moduleId)
				},
				success: function(results1) {
					if (results1.errorCode == 200) {

						list[list.length] = results1.data;
						editModule();

					} else {
						alert("添加失败");
					}
				}
			})
		})

	}
	
	$(".diy-cirl").on('click',".show_head_checkbox",function(){
		var checked = $(this).is(":checked");
		var $parent = $(this).parents(".item");
		var index = parseInt($parent.attr("index"));
		var extData = $.parseJSON(list[index].extData);
		if(checked) {		
			extData.showHeader=1;
		}else {
			extData.showHeader=0;
		}	
		list[index].extData = JSON.stringify(extData);
	});
	
	$(".diy-cirl").on('click',".show_line_checkbox",function(){
		var checked = $(this).is(":checked");
		var $parent = $(this).parents(".item");
		var index = parseInt($parent.attr("index"));
		if(checked) {
			list[index].showLine = 1;
		}else {
			list[index].showLine = 0;
		}
	});
	
	$(".diy-cirl").on("blur",".header_name",function(){
		var value = $(this).val()
		var checked = $(this).is(":checked");
		var $parent = $(this).parents(".item");
		var index = parseInt($parent.attr("index"));
		list[index].name = value;
	})
	
	$(".diy-cirl").on("keyup",".header_name",function(){
		var value = $(this).val()
		var checked = $(this).is(":checked");
		var $parent = $(this).parents(".item");
		var index = parseInt($parent.attr("index"));
		list[index].name = value;
	})

	//innerContainer事件
	$(".diy-phone").on('click', '.innerContainer',function() {
		var index = parseInt($(this).attr("index"));
		var moduleIdAnotherId = parseInt($(this).attr("moduleId")); //这个moduleId表明是哪种类型的模块
		var featureId = $(this).attr("featureId");
		var extData = $(this).attr("extData");
		var extDataTpl;
		var extDataRenderMode;
		var extDataObj;

		if (extData!= "" && extData != null && extData != undefined) {			
			extDataObj = JSON.parse(extData);
		}	

		var checkedValue;

		var id = $(this).attr("id"); //唯一标识的id;
		if (moduleIdAnotherId == 9) { //如果是精选大banner或者专题,则弹出编辑选择框,其余直接跳转编辑页
			initCtrlHtml(bannerEditHtml,index);
			if (extData!= "" && extData != null && extData != undefined) {
				extDataTpl = parseInt(extDataObj.tpl);
			}
			if (extDataTpl == 2) {
				checkedValue = "newFormat";
			} else {
				checkedValue = "oldFormat";
			}

			initRadioEvent(moduleIdAnotherId, index, checkedValue, "newFormat", "oldFormat");

			$(".bannerFormatEdit").click(function() {
				bannerChoose = $("input[name='bannerFormat']:checked").val();
				if (bannerChoose == "" || bannerChoose == undefined) {
					alert("请至少选择一种版式");
				} else {
					if (bannerChoose == "newFormat") { //跳转到新版式编辑
						var extData = {};
						extData.tpl = 2;
						list[index].extData = JSON.stringify(extData);
						bannerChoose = "";

						$(".bannerFormatEdit").parent("a").attr("href", "advertisement/getByFeatureId/" + id);
					} else { //跳转到旧版式编辑
						list[index].extData = "";
						bannerChoose = "";
						$(".bannerFormatEdit").parent("a").attr("href", "advertisement/getByFeatureId/" + id);
					}
				}
			})
		} else if (moduleIdAnotherId == 22) {

			initCtrlHtml(specialEditHtml,index);

			$(".specialManage").click(function() { //跳转到管理专题
				$(".specialManage").parent("a").attr("href", "/cms/manage/intensivePost/list");
			})
			

			$(".relateManage").click(function() { //跳转到关联专题
				$(".relateManage").parent("a").attr("href", "/cms/manage/module/getAllTopic?featureKeyId=" + id);
			})
		} else if(moduleIdAnotherId == 19){
			initCtrlHtml(greatGoodsEditHtml,index);
			$(".greatGoodsManage").click(function() { //跳转到管理精选好物
				$(".greatGoodsManage").parent("a").attr("href", "/cms/manage/intensivePost/list");
			})

			$(".relateGreatGood").click(function() { //跳转到关联精选好物
				$(".relateGreatGood").parent("a").attr("href", "/cms/manage/module/getAllTopic?featureKeyId=" + id);
			})
			
		} else if (moduleIdAnotherId == 29) { //精品拍
			
			if (extData!= "" && extData != null && extData != undefined) {
				extDataTpl = parseInt(extDataObj.tpl);
			}
			
			if (extDataTpl == 2) {
				checkedValue = "newAuctionFormat";
			} else {
				checkedValue = "oldAuctionFormat";
			}
			initCtrlHtml(boutiqueEditHtml,index);
			initRadioEvent(moduleIdAnotherId, index, checkedValue, "newAuctionFormat", "oldAuctionFormat");

		} else if (moduleIdAnotherId == 4) {

			if (extData!= "" && extData != null && extData != undefined) {
				extDataTpl = parseInt(extDataObj.tpl);
			}

			if (extDataTpl == 2) {
				checkedValue = "newcateFormat";
			} else {
				checkedValue = "oldcateFormat";
			}
			initCtrlHtml(categoryEditHtml,index);
			initRadioEvent(moduleIdAnotherId, index, checkedValue, "newcateFormat", "oldcateFormat");

			$(".cateFormatEdit").click(function() {
				$(".cateFormatEdit").parent("a").attr("href", "/cms/manage/module/getFeatureItemByFeatureId?id=" + id);
			})
		}
		else if(moduleIdAnotherId == 33){  //大师推荐
			
			initCtrlHtml(masterEditHtml,index);
			$(".masterRec").parent("a").attr("href", "/cms/manage/module/bindingBigTeacherList?featureKeyId=" + id);
			
			}			 
		else if (moduleIdAnotherId == 1) { //图片专题或5精选商品
			if (extData!= "" && extData != null && extData != undefined) {
				extDataTpl = parseInt(extDataObj.tpl);
			}
			if (extDataTpl == 1) {
				checkedValue = "picFormatOne";
			} else if (extDataTpl == 2) {
				checkedValue = "picFormatTwo";
			} else if (extDataTpl == 3) {
				checkedValue = "picFormatThree";
			} else if (extDataTpl == 4) {
				checkedValue = "picFormatFour";
			}
			initCtrlHtml(pictureEditHtml,index);
			initRadioEvent(moduleIdAnotherId, index, checkedValue, "picFormatOne", "picFormatTwo", "picFormatThree", "picFormatFour");

			$(".picEdit").click(function() {
				//跳转到图片专题
				$(".picEdit").parent("a").attr("href", "/cms/manage/module/getFeatureItemByFeatureId?id=" + id);
			})
		} else {
			//跳转
			//$(".diy-cirl").css("display", "none");
			initCtrlHtml(baseEditHtml+endEditHtml,index);
			$(".baseEdit").click(function() {
				
				$(".baseEdit").parent("a").attr("href", "/cms/manage/module/getFeatureItemByFeatureId?id=" + id);
			})
			

		}
	})

	//加载右边编辑框
	function initCtrlHtml(editHtml,index) {

		$(".diy-cirl").css("display", "block");
		editHtml = editHtml.replace('_index_placeholder',index)
		var new_editHtml = $(editHtml);
		initUI(new_editHtml);
		$(".diy-cirl").html(new_editHtml);
		
		var  obj = list[index];
		var extData = $.parseJSON(obj.extData);
		if(extData && extData.showHeader && extData.showHeader ==1){
			new_editHtml.find(".show_head_checkbox").attr("checked","checked");
		}else {
			new_editHtml.find(".show_head_checkbox").removeAttr("checked");
		}
		
		if(obj.showLine && obj.showLine == 1) {
			new_editHtml.find(".show_line_checkbox").attr("checked","checked");
		}else {
			new_editHtml.find(".show_line_checkbox").removeAttr("checked");
		}
		new_editHtml.find(".header_name").val(obj.name);
		//		
	}

	//对应的单选框选择
	function initRadioEvent(moduleIdAnotherId, index, checkValue,newValue, oldValue, threeValue, FourValue) {

		$("input[value='" + checkValue + "']").attr("checked", "checked");

		$("input[value='" + newValue + "']").click(function() {
			if (moduleIdAnotherId == 9) {
				var extData = {};
				extData.tpl = 2;
			} else if (moduleIdAnotherId == 29) {
				var extData={};
				extData.tpl = 2;
			} else if (moduleIdAnotherId == 4) {
				var extData = {};
				extData.tpl = 2;
			} else {
				var extData = {};
				extData.tpl = 1;
			}

			list[index].extData = JSON.stringify(extData);
		})

		$("input[value='" + oldValue + "']").click(function() {

			if (moduleIdAnotherId == 9 || moduleIdAnotherId == 29) {
				list[index].extData = "";
			} else if (moduleIdAnotherId == 4) {
				var extData = {};
				extData.showHeader = 1;
				list[index].extData = JSON.stringify(extData);
			} else {
				var extData = {};
				extData.tpl = 2;
				list[index].extData = JSON.stringify(extData);
			}

		})

		$("input[value='" + threeValue + "']").click(function() {
			var extData = {};
			extData.tpl = 3;
			list[index].extData = JSON.stringify(extData);

		})

		$("input[value='" + FourValue + "']").click(function() {
			var extData = {};
			extData.tpl = 4;

			list[index].extData = JSON.stringify(extData);

		})
	}

	//阻止事件冒泡和默认事件
	function dealEvent() {
		var e = arguments.callee.caller.arguments[0] || event;
		if (e && e.stopPropagation) { // this code is for Mozilla and Opera
			e.stopPropagation();
			e.preventDefault();
		} else if (window.event) { // this code is for IE 
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		$(".diy-cirl").css("display", "none");
	}

	//处理模块
	function editModule() {
		var modulsHtml = '';
		for (var i = 0; i < list.length; i++) {
			if (list[i].moduleId == 9 ||list[i].moduleId == 29 || list[i].moduleId == 1 || list[i].moduleId == 4) {
				modulsHtml += "<div><div class='innerContainer' extData='" + list[i].extData + "' index=" + i + " id=" + list[i].id + "  enable=" + list[i].enable + " featureId=" + list[i].featureId + " moduleId=" + list[i].moduleId + " orderNum=" + list[i].orderNum + ">" + list[i].name + "<span class='editContainer'><span class='upline'>上线</span><span class='downLine'>下线</span><span class='delete'>删除</span><span class='moveDown'>下移</span><span class='moveUp'>上移</span></span></div></div>";
			}
			else if(list[i].moduleId == 22||list[i].moduleId == 19){
				modulsHtml += "<div><div class='innerContainer'  index=" + i + " id=" + list[i].id + "  enable=" + list[i].enable + " featureId=" + list[i].featureId + " moduleId=" + list[i].moduleId + " orderNum=" + list[i].orderNum + ">" + list[i].name + "<span class='editContainer'><span class='upline'>上线</span><span class='downLine'>下线</span><span class='delete'>删除</span><span class='moveDown'>下移</span><span class='moveUp'>上移</span></span></div></div>";
			}
			else {
				if (list[i].moduleId == 33) {
					modulsHtml += '<div><div class="innerContainer" index=' + i + ' id=' + list[i].id + '  enable=' + list[i].enable + ' featureId=' + list[i].featureId + ' moduleId=' + list[i].moduleId + ' orderNum=' + list[i].orderNum + '>' + list[i].name  + '<span class="editContainer"><span class="upline">上线</span><span class="downLine">下线</span><span class="delete">删除</span><span class="moveDown">下移</span><span class="moveUp">上移</span></span></div></div>';
				} else {
					modulsHtml += '<div><div class="innerContainer" index=' + i + ' id=' + list[i].id + '  enable=' + list[i].enable + ' featureId=' + list[i].featureId + ' moduleId=' + list[i].moduleId + ' orderNum=' + list[i].orderNum + '>' + list[i].name  + '<span class="editContainer"><span class="upline">上线</span><span class="downLine">下线</span><span class="delete">删除</span><span class="moveDown">下移</span><span class="moveUp">上移</span></span></div></div>';
				}

			}

		}
		var new_modulsHtml = $(modulsHtml);
		initUI(new_modulsHtml);
		$(".diy-phone-contain").html(new_modulsHtml);

		for (var i = 0; i < list.length; i++) {
			list[i].enable = parseInt(list[i].enable);
			if (list[i].enable == 1) {
				$(".upline").eq(i).hide();
				$(".downLine").eq(i).show();
			} else if (list[i].enable == 0) {
				$(".downLine").eq(i).hide();
				$(".upline").eq(i).show();
			}

			if (i == 0) {
				$(".moveUp").eq(i).hide();
			} else if (i == list.length - 1) {

				$(".moveDown").eq(i).hide();
			}

		}

	}

	//上线
	$(".diy-phone").on('click', '.upline',function() {
		dealEvent();
		var index = parseInt($(this).parents(".innerContainer").attr("index"));
		var type = $(this).parents(".innerContainer").attr("moduleId"); //模块类型;
		list[index].enable = 1;
		editModule();
	})

	//下线
	$(".diy-phone").on('click', '.downLine',function() {
		dealEvent();
		var index = parseInt($(this).parents(".innerContainer").attr("index"));
		var type = $(this).parents(".innerContainer").attr("moduleId"); //模块类型;
		list[index].enable = 0;
		editModule();

	})

	//删除某一项
	$(".diy-phone").on('click', '.delete',function(event) {
		dealEvent();
		var index = parseInt($(this).parents(".innerContainer").attr("index"));
		var type = $(this).parents(".innerContainer").attr("moduleId"); //模块类型;
		list.splice(index, 1);

		var r = confirm("你确定要删除这一项吗?");
		if (r == true) {
			editModule();
		}
	});

	//保存数据
	$(".saveData").click(function() {
		featureJsonValues = JSON.stringify(list);
		utils.jsonp({
			url: "modules/updateModule",
			type: "POST",
			params: {
				"featureJsonValues": featureJsonValues,
				"moduleId": moduleId
			},
			success: function(resul) {
				if (resul.errorCode == 200) {
					alert("更新成功");
				} else {
					alert(resul.moreInfo);
				}
			}
		})
	})

	//下移
	$(".diy-phone").on('click', '.moveDown',function() {

		dealEvent();

		var index = parseInt($(this).parents(".innerContainer").attr("index"));
		var type = $(this).parents(".innerContainer").attr("moduleId"); //模块类型;   	 	   
		var a1 = list[index + 1];
		var a2 = list[index];

		var a1orderNum = a1.orderNum;
		var a2orderNum = a2.orderNum;

		list[index] = a1;
		list[index + 1] = a2;

		list[index].orderNum = a2orderNum;
		list[index + 1].orderNum = a1orderNum;

		editModule();

	});

	//上移
	$(".diy-phone").on('click', '.moveUp',function() {

		dealEvent();

		var index = $(this).parents(".innerContainer").attr("index");
		var type = $(this).parents(".innerContainer").attr("moduleId"); //模块类型;
		var a1 = list[index];
		var a2 = list[index - 1];

		var a1orderNum = a1.orderNum;
		var a2orderNum = a2.orderNum;

		list[index - 1] = a1;
		list[index] = a2;

		list[index].orderNum = a1orderNum;
		list[index - 1].orderNum = a2orderNum;

		editModule();

	});

})